package com.will.network.images;

import android.content.Context;
import android.graphics.Bitmap;

import com.android.volley.toolbox.ImageLoader.ImageCache;


/**
 * Created by will on 14-9-10.
 */
public class ImageL2Cache implements ImageCache {

    private final String TAG = "ImageL2Cache";
    /**
     * Image cache implementation
     */
    private ImageCache mImageLruMemoryCache;
    private ImageCache mImageLruDiskCache;

    public ImageL2Cache(Context context, ImageCache imageLruMemoryCache, String uniqueName, int diskCacheSize, Bitmap.CompressFormat compressFormat, int quality) {
        mImageLruMemoryCache = imageLruMemoryCache;
        mImageLruDiskCache = new ImageLruDiskCache(context, uniqueName, diskCacheSize, compressFormat, quality);
    }

    public void clearDiskCache(){
        ((ImageLruDiskCache)mImageLruDiskCache).clearCache();
    }

    public ImageCache getMemImageCache(){
        return mImageLruMemoryCache;
    }

    public ImageCache getDiskImageCache(){
        return mImageLruDiskCache;
    }

    @Override
    public Bitmap getBitmap(String key) {
        try {
            Bitmap bmp = mImageLruMemoryCache.getBitmap(key);
            if(bmp == null) {
                bmp = mImageLruDiskCache.getBitmap(key);
                if (bmp != null){
                    mImageLruMemoryCache.putBitmap(key, bmp);
//                    Log.d(TAG, "Load image from disk cache: " + key);
                }
            }else {
//                Log.d(TAG, "Load image from memory cache: " + key);
            }
            return bmp;
        } catch (NullPointerException e) {
            throw new IllegalStateException("Cache Not initialized");
        }
    }

    @Override
    public void putBitmap(String key, Bitmap bitmap) {
        try {
            mImageLruMemoryCache.putBitmap(key, bitmap);
            mImageLruDiskCache.putBitmap(key, bitmap);
        } catch (NullPointerException e) {
            throw new IllegalStateException("Cache Not initialized");
        }
    }

}
